package com.futao.techsharingmq.basic.concept.simple.book;

import com.futao.techsharingmq.basic.concept.simple.MqChannelUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 将exchange与exchange绑定
 * 将exchange的消息路由到另外的exchange，再路由到queue
 *
 * @author futao@gmail.com
 * @date 2021/11/2
 */
public class Exchange2Exchange {
    public static void main(String[] args) throws IOException {
        // 获取channel
        Channel channel = MqChannelUtils.createChannel();

        //定义topic类型的交换机e-pre
        channel.exchangeDeclare("e-pre", BuiltinExchangeType.TOPIC);

        // 定义fanout类型的交换机e-a, e-b, e-ab
        channel.exchangeDeclare("e-a", BuiltinExchangeType.FANOUT);
        channel.exchangeDeclare("e-b", BuiltinExchangeType.FANOUT);
        channel.exchangeDeclare("e-ab", BuiltinExchangeType.FANOUT);

        // 将e-pre和三个交换机绑定，并且指定路由规格，注意这里使用的是#exchangeBind方法
        channel.exchangeBind("e-a", "e-pre", "r-a");
        channel.exchangeBind("e-b", "e-pre", "r-b");
        // 绑定多个路由键r-a,r-b
        channel.exchangeBind("e-ab", "e-pre", "r-a");
        channel.exchangeBind("e-ab", "e-pre", "r-b");

        // 定义匿名队列并获取生成的匿名队列名称
        String queue1 = channel.queueDeclare().getQueue();
        // 将匿名队列与三个交换机绑定
        channel.queueBind(queue1, "e-a", "");
        String queue2 = channel.queueDeclare().getQueue();
        channel.queueBind(queue2, "e-b", "");
        String q3 = channel.queueDeclare().getQueue();
        channel.queueBind(q3, "e-ab", "");

        // 发送100条消息
        for (int i = 0; i < 1000; i++) {
            // 生成路由键
            String rk = "r-b";
            if (i % 2 == 0) {
                rk = "r-a";
            }
            //将消息投递到e-pre交换机
            channel.basicPublish("e-pre", rk, new AMQP.BasicProperties(), "success".getBytes(StandardCharsets.UTF_8));
        }
    }
}
